/**
 * Copyright (c) 2012-2016, www.tinygroup.org (luo_guo@icloud.com).
 * <p>
 * Licensed under the GPL, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.tinygroup.remoteconfig.zk.manager.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.tinygroup.commons.tools.VariableUtil;
import org.tinygroup.exception.BaseRuntimeException;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;
import org.tinygroup.remoteconfig.IRemoteConfigConstant;
import org.tinygroup.remoteconfig.RemoteConfigReadClient;
import org.tinygroup.remoteconfig.config.ConfigPath;
import org.tinygroup.remoteconfig.config.ConfigValue;
import org.tinygroup.remoteconfig.config.Environment;
import org.tinygroup.remoteconfig.config.Module;
import org.tinygroup.remoteconfig.manager.EnvironmentManager;
import org.tinygroup.remoteconfig.zk.client.ZKManager;
import org.tinygroup.remoteconfig.zk.config.RemoteConfig;
import org.tinygroup.remoteconfig.zk.config.RemoteEnvironment;
import org.tinygroup.remoteconfig.zk.utils.PathHelper;


public class ZKConfigClientImpl implements RemoteConfigReadClient {

    protected static final Logger LOGGER = LoggerFactory
            .getLogger(ZKConfigClientImpl.class);

    ConfigPath configPath;

    private EnvironmentManager environmentManager;

    public EnvironmentManager getEnvironmentManager() {
        if (environmentManager == null) {
            environmentManager = new EnvironmentManagerImpl();
        }
        return environmentManager;
    }

    public void setEnvironmentManager(EnvironmentManager environmentManager) {
        this.environmentManager = environmentManager;
    }

    public boolean exists(String key) throws BaseRuntimeException {
        String path = PathHelper.createPath(configPath);
        LOGGER.logMessage(LogLevel.DEBUG, "远程配置，判断节点是否存在[key={0} ,path={1}]", key, path);
        try {
            return ZKManager.exists(key, configPath);
        } catch (Exception e) {
            LOGGER.logMessage(LogLevel.ERROR, "远程配置，判断节点是否存在[key={0} ,path={1}]", e, key, path);
        }
        return false;
    }

    public ConfigValue get(String key) throws BaseRuntimeException {
        String path = PathHelper.createPath(configPath);
        LOGGER.logMessage(LogLevel.DEBUG, "远程配置，获取节点[key={0} ,path={1}]", key, path);
        try {
            return ZKManager.get(key, configPath);
        } catch (Exception e) {
            LOGGER.logMessage(LogLevel.ERROR, "远程配置，获取节点失败[key={0} ,path={1}]", e, key, path);
        }
        return null;
    }


    public Map<String, ConfigValue> getAll() throws BaseRuntimeException {
        Map<String, ConfigValue> itemMap = new HashMap<String, ConfigValue>();
        Map<String, ConfigValue> defaultItemMap = new HashMap<String, ConfigValue>();
        String path = PathHelper.createPath(configPath);
        LOGGER.logMessage(LogLevel.DEBUG, "远程配置，批量获取节点[path={0}]", path);
        Environment defaultEnvironment = getEnvironmentManager().get(IRemoteConfigConstant.DEFAULT_ENV_NAME, configPath.getVersionName(), configPath.getProductName());
        Environment environment = getEnvironmentManager().get(configPath.getEnvironmentName(), configPath.getVersionName(), configPath.getProductName());
        if (environment != null && defaultEnvironment != null) {
            //取默认环境
            getConfig(defaultEnvironment, defaultItemMap);

            //取指定模块
            getConfig(environment, itemMap);
            for (String key : itemMap.keySet()) {
                if (defaultItemMap.get(key) != null) {
                    defaultItemMap.put(key, itemMap.get(key));
                }
            }
        }
        return defaultItemMap;
    }

    public void start() {
    	//配置中心客户端如果获取配置失败，则获取环境变量
    	RemoteConfig config = RemoteEnvironment.getConfig();
    	if (config == null) {
    		config = RemoteEnvironment.load();
		}
    	if (isError(config)) {
    		LOGGER.logMessage(LogLevel.INFO, "配置中心，本地配置配置错误...");
    		//读取环境变量
    		LOGGER.logMessage(LogLevel.INFO, "尝试获取环境变量相关配置...");
    		getSystemEnv(config);
    		//打印配置
    		//...
    		if (isError(config)) {
    			throw new RuntimeException("配置信息不合法，远程配置拉取失败...");
    		}
		}
        setConfigPath(getConfigPath(config));
        ZKManager.setConfig(config);
        ZKManager.start();
    }

    public void stop() {
        ZKManager.stop();
    }

    private void getSystemEnv(RemoteConfig config){
    	
    	String url = VariableUtil.getEnvVariable(IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_URL);
    	String app = VariableUtil.getEnvVariable(IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_APP);
    	String env = VariableUtil.getEnvVariable(IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_ENV);
    	String version = VariableUtil.getEnvVariable(IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_VER);
    	String username = VariableUtil.getEnvVariable(IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_USERNAME);
    	String password = VariableUtil.getEnvVariable(IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_PASSWORD);
    	LOGGER.logMessage(LogLevel.INFO, "系统变量[{0}={1}]" ,IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_URL ,url);
    	LOGGER.logMessage(LogLevel.INFO, "系统变量[{0}={1}]" ,IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_APP ,app);
    	LOGGER.logMessage(LogLevel.INFO, "系统变量[{0}={1}]" ,IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_ENV ,env);
    	LOGGER.logMessage(LogLevel.INFO, "系统变量[{0}={1}]" ,IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_VER ,version);
    	LOGGER.logMessage(LogLevel.INFO, "系统变量[{0}={1}]" ,IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_USERNAME ,username);
    	LOGGER.logMessage(LogLevel.INFO, "系统变量[{0}={1}]" ,IRemoteConfigConstant.SYS_ENV_TINY_CONFIG_PASSWORD ,password);
    	config.setUrls(url);
    	config.setApp(app);
    	config.setEnv(env);
    	config.setUsername(username);
    	config.setPassword(password);
    	config.setVersion(version);
    }
    
    private boolean isError(RemoteConfig config){
    	if (config == null || StringUtils.isBlank(config.getApp())
    			|| StringUtils.isBlank(config.getEnv()) || StringUtils.isBlank(config.getVersion())) {
			return true;
		}
    	return false;
    }
    
    private ConfigPath getConfigPath( RemoteConfig config) {
        ConfigPath configPath = new ConfigPath();
        if (config != null) {
            configPath.setProductName(config.getApp());
            configPath.setVersionName(config.getVersion());
            configPath.setEnvironmentName(config.getEnv());
        }
        return configPath;
    }

    public void setConfigPath(ConfigPath configPath) {
        this.configPath = configPath;

    }

    private void getConfig(Environment environment, Map<String, ConfigValue> itemMap) {
        List<Module> modules = environment.getModules();
        for (Module subModule : modules) {
            ConfigPath tempConfigPath = new ConfigPath();
            tempConfigPath.setProductName(configPath.getProductName());
            tempConfigPath.setVersionName(configPath.getVersionName());
            tempConfigPath.setEnvironmentName(environment.getName());
            recursionModule(subModule, tempConfigPath, itemMap);
        }
    }

    /**
     * 递归遍历模块
     *
     * @param parentModule
     * @param configPath
     * @param itemMap
     */
    private void recursionModule(Module parentModule, ConfigPath configPath, Map<String, ConfigValue> itemMap) {
        if (configPath == null) {
            return;
        }
        configPath.setModulePath(PathHelper.getConfigPath(configPath.getModulePath(), parentModule.getName()));
        Map<String, ConfigValue> subItemMap = null;
        try {
            subItemMap = ZKManager.getAll(configPath);
        } catch (Exception e) {
            return;
        }
        itemMap.putAll(subItemMap);
        for (String key : subItemMap.keySet()) {
            itemMap.put(key, subItemMap.get(key));
        }
        for (Module subModule : parentModule.getSubModules()) {
            recursionModule(subModule, configPath, itemMap);
        }
    }

}
